package MTT::Form::Report;

use HTML::FormHandler::Moose;
extends 'HTML::FormHandler::Model::DBIC';
with 'HTML::FormHandler::Render::Simple';
use namespace::autoclean;

use utf8;

use Data::Dumper;
use POSIX qw(strftime);
use MTT::Libs::ObjectAccess;

has '+item_class' => ( default => 'Report' );

#has '+action' => ( default => '/users/register' );

has 'name' => ( is => 'ro', default => 'templateForm' );


has_field 'switch_type' => ( 
	type => 'Multiple', 
	label => '', 
	size => 9, 
	style => 'width: 175px', 
	disabled => 0,
	javascript => 'onchange="get_switches(this)"' );
has_field 'switch' => ( type => 'Multiple', label => '', size => 9, style => 'width: 230px' );
has_field 'switch_do' => ( type => 'Multiple', label => '', size => 9, style => 'width: 230px' );

has_field 'date_from' => ( type => 'Text', label => 'Начальная дата' );
has_field 'date_to' => ( type => 'Text', label => 'Конечная дата' );

has_field 'company_box' => ( type => 'Checkbox', label => 'Компания' );
has_field 'company' => ( type => 'Multiple', label => '', style => 'width: 230px' );
has_field 'city_box' => ( type => 'Checkbox', label => 'Город' );
has_field 'city' => ( type => 'Multiple', label => '', style => 'width: 230px' );
has_field 'region_box' => ( type => 'Checkbox', label => 'Регион' );
has_field 'region' => ( type => 'Multiple', label => '', style => 'width: 230px' );
has_field 'federal_box' => ( type => 'Checkbox', label => 'Округ' );
has_field 'federal' => ( type => 'Multiple', label => '', style => 'width: 230px' );

has_field 'params' => ( type => 'Hidden' );
has_field 'groups' => ( type => 'Hidden' );

has_field 'report_name' => ( type => 'Text', label => 'Название отчета' );
has_field 'comment' => ( type => 'TextArea', label => 'Комментарий', cols => '42', size => '13' );

has_field 'run_report' => ( type => 'Submit', value => 'Запустить отчет' );
has_field 'save_report' => ( 
	type => 'Submit', 
	value => 'Сохранить шаблон', 
	javascript => 'onclick="save_report()"' 
);
has_field 'save_report_as' => ( type => 'Submit', value => 'Сохранить шаблон как' );

sub default_date_from {
	my ($self) = @_;
	return strftime('%Y-%m-%d 00::00', localtime);
}

sub default_date_to {
	my ($self) = @_;
	return strftime('%Y-%m-%d %H:%M', localtime);
}

sub options_switch_type {
	my ($self) = @_;
	return unless $self->ctx;

	my $c = $self->ctx;

	my $oa = MTT::Libs::ObjectAccess->instance();
	my $switches = {};
	my ($id_type, $id_switch) = ( $c->req->args->[0], $c->req->args->[1] );

	my @options;

	if ( !$id_type && !$id_switch ) {
		my @types = $c->model('DBIC::SwitchType')->all();

		foreach my $type ( @types ) {
			next unless $oa->check_objects_access($c, 'Оборудование', $type->id) || $c->check_user_roles('admin');
			push @options, { value => $type->id, label => $type->type};
		}
	}
	elsif ( $id_type ) {
		if ( $oa->check_objects_access($c, 'Оборудование', $id_type) || $c->check_user_roles('admin') ) {
			my $type = $c->model('DBIC::SwitchType')->find($id_type);
			if ($type) {
				push @options, { value => $type->id, label => $type->type};
			}
		}
	}

	$self->field('switch_type')->disabled(1) if $id_switch;

	return @options;
}

sub options_switch {
	my ($self) = @_;
	return unless $self->ctx;

	my @options;

	return @options;
}

sub options_switch_do {
	my ($self) = @_;
	return unless $self->ctx;

	my $c = $self->ctx;
	my $oa = MTT::Libs::ObjectAccess->instance();
	my($id_type, $id_switch) = ($c->req->args->[0], $c->req->args->[1]);

	my @options;
	if ($id_switch) {
		my $switch = $c->model('DBIC::Switch')->find($id_switch);
		push @options, {value => $switch->id, label => $switch->descr} if $switch;
	}
	else {
		if ( $c->stash->{init_params} ) {

			foreach my $id ( @{ $c->stash->{init_params}->{switch_do} } ) {
				my $switch = $c->model('DBIC::Switch')->find($id);
				if ($switch) {
					push @options, {value => $switch->id, label => $switch->descr}; 
				}
			}
		}
		elsif ($id_type) {
				my $switches = $c->model('DBIC::Switch')->search({id_type => $id_type});
				while ( my $switch = $switches->next() ) {
					push @options, {value => $switch->id, label => $switch->descr};
				}
		}

	}

	return @options;
}

sub parameters {
	my ($self) = @_;
	
	my	%params = (
		 BHCTIME => 'Начало ЧНН',
		 BHLLOAD => 'Суммарная разговорная нагрузка',
		 ERLANG => 'Пропускная способнось направления',
		 MATTEMPTBHCA => 'Попытки занятия',
		 MLOAD => 'Энтенсивность нагрузки, Эрл',
		 NBLOCKDEV => 'Число недоступных каналов',
		 NCONVSEC => 'Время разговора',
		 NDEV => 'Число каналов',
		 NDEVLASTREQ => 'Требуемое число каналов для потерь',
		 NDEVREQ => 'Требуемое число каналов',
		 NSEIZREQ => 'Время занятия, сек',
		 PABAND => 'Отказы для трансгруппы, %',
		 PANSW => 'КЗО, %',
		 PCALCLOST => 'Рассчетная вероятность потерь, %',
		 PCHANNELUSAGE => 'КИК, %',
		 PLOAD => 'Коэффициент концентрации нагрузки',
		 PLOST => 'Потери на пути последнего выбора',
		 SUMLOAD => 'Суммарная нагрузка за период',
	 );

	my %groups = (
		'Компания' => '',
		'Net Type' => '',
		'Route Addr' => '',
		'Route Name' => '',
		'Switch Name' => '',
		'Город' => '',
		'Регион' => '',
		'Округ' => '',
		'Дата' => '',
		'Время' => '',
		'Route Type' => ''
	);
	
	my $result = {params => [], groups => []};
	if ( my $init_params = $self->ctx->stash->{init_params} ) {
		foreach my $key ( @{ $init_params->{param_do} } ) {
			push @{ $result->{params_do} }, [ $key, $params{$key} ];
			delete $params{$key};
		}
		foreach my $key ( @{ $init_params->{group_do} } ) {
			push @{ $result->{groups_do} }, [ $key, $params{$key} ];
			delete $groups{$key};
		}
	}

	foreach my $key ( keys %params ) {
		push @{ $result->{params} }, [ $key, $params{$key} ];
	}
	push @{ $result->{groups} }, [ $_, $groups{$_} ] foreach keys %groups;

	return $result;
}


__PACKAGE__->meta->make_immutable;
1;


